from flask import request, Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import Tags
import uuid
from flask_jwt_extended import jwt_required
from utils.h_result import HResult

bp = Blueprint('tags', __name__, url_prefix='/tags/')

class AddTag(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        name = data.get('name')
        
        if not name:
            return HResult().get_result('error', '参数错误!')
            
        tag = Tags(
            id=str(uuid.uuid4()),
            name=name
        )
        
        if 'style' in data:
            tag.style = data['style']
            
        db.session.add(tag)
        db.session.commit()
        return HResult().get_result('success', '添加成功!', tag.to_dict())

class DeleteTag(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        tag_ids = data['ids']
        
        for tag_id in tag_ids:
            tag = Tags.query.filter_by(id=tag_id).first()
            if tag:
                db.session.delete(tag)
                
        db.session.commit()
        return HResult().get_result('success', '删除成功!')

class UpdateTag(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        tag_id = data['id']

        tag = Tags.query.filter_by(id=tag_id).first()
        if not tag:
            return HResult().get_result('error', '标签不存在!')
            
        for key, value in data.items():
            if key != 'id':
                setattr(tag, key, value)
                
        db.session.commit()
        return HResult().get_result('success', '修改成功!')

class TagInfo(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        tag_id = request.args.get('id')
        tag = Tags.query.filter_by(id=tag_id).first()
        
        if not tag:
            return HResult().get_result('error', '标签不存在!')
            
        return HResult().get_result('success', data=tag.to_dict())

class QueryAllTags(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        tags = Tags.query.all()
        return HResult().get_result('success', data=[tag.to_dict() for tag in tags])

api = Api(bp)
api.add_resource(AddTag, '/add/', endpoint='add')
api.add_resource(DeleteTag, '/delete/', endpoint='delete')
api.add_resource(UpdateTag, '/update/', endpoint='update')
api.add_resource(TagInfo, '/info/', endpoint='info')
api.add_resource(QueryAllTags, '/list/', endpoint='list') 